﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.TR.Library;
using ZX.TR.Bussiness;
using System.Threading;
using ZX.EHR.Library;
using ZX.BLL.Extend;

namespace ZX.WebApp.TR
{
    public partial class QuestionnaireOnline : BasePage
    {
        public static string startTime = "00:00:00";//开始时间
        public int longTime = 0;                    //考试时长
        int num = 0; //单题时题目索引
        public string message = ""; //倒计时
        BTrQuestionnaireSubject bTrQuestionnaireSubject = new BTrQuestionnaireSubject();   //业务对象
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnPre.Enabled = false;
                //单题索引
                Session["nums"] = num;
                Session.Timeout = 150;
                V_TrQuestionnaire vtq = new V_TrQuestionnaire();
                V_TrSendQuestion vtsq = new V_TrSendQuestion();
                string strId = Request.QueryString["id"];
                if (strId != "")
                {
                    pnlEn.Enabled = false;
                    vtsq = bTrQuestionnaireSubject.GetAllTrSendQuestionInfoById(new Guid(strId));
                    strId = vtsq == null ? "00000000-0000-0000-0000-000000000000" : vtsq.TrQuestionnaireID.ToString();
                    vtq = bTrQuestionnaireSubject.GetAllQuestionnaireInfoById(new Guid(strId));
                    if (vtq != null)
                    {
                        lblWjName.Text = vtq.QuestionnaireName;
                        txtAim.Text = vtq.QAim;
                        txtDept.Text = vtq.DeptName;
                        txtKnown.Text = vtq.QNotice;
                        txtPoint.Text = vtq.PointSum.ToString();
                        txtSum.Text = vtq.SubjectSum.ToString();
                        txtTime.Text = vtq.QTimeLength.ToString();
                        Session["trquestion"] = vtq.TrQuestionnaireID;
                    }
                    Session["times"] = null;
                    bind(Session["trquestion"] == null ? Guid.NewGuid() : new Guid(Session["trquestion"].ToString()), 9999, num);
                    Session["count"] = rptList.Items.Count;
                    if (num == rptList.Items.Count - 1)
                    {
                        btnNext.Enabled = false;
                    }
                }
            }
        }
        private void bind(Guid guid, int topNum, int pageNum)
        {
            DatUser duser = Session["User"] as DatUser;
            IList<V_TrExam> vteList = bTrQuestionnaireSubject.GetExamListById(guid);
            rptList.DataSource = vteList;
            rptList.DataBind();
        }
        protected void btnBegin_Click(object sender, EventArgs e)
        {
            startTime = DateTime.Now.ToLongTimeString();
            pnlList.Visible = true;
            btnBegin.Enabled = false;
            pnlEn.Enabled = true;
            btnSave.Visible = true;
            rbtnSelect.Enabled = false;
            Session["times"] = DateTime.Now.ToLongTimeString();
        }
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            longTime = Convert.ToInt32(txtTime.Text);
            DateTime date = System.DateTime.Now; //60分钟
            DateTime date2 = Session["times"] == null ? DateTime.Now : Convert.ToDateTime(Session["times"].ToString()).AddMinutes(longTime);
            TimeSpan ts = date2.Subtract(date);
            if (ts.Hours == 0 && ts.Minutes == 0 && ts.Seconds == 0)
            {
                saveExam(true);
                //ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, UpdatePanel1.GetType(), "error", "window.showModalDialog('Pop.aspx', 'newwindow', 'dialogWidth:400px;DialogHeight=300px;center: yes;help:no;resizable:no;status:no');", true);
                //ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, UpdatePanel1.GetType(), "error", "window.open ('Pop.aspx', 'newwindow', 'height=450, width=550, top=120,left=250, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');", true);
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "", "alert('时间到！');closeWins()", true);

            }

            message += ((ts.Hours < 10) ? ("0" + ts.Hours.ToString()) : ts.Hours.ToString());
            message += ":" + (ts.Minutes < 10 ? ("0" + ts.Minutes.ToString()) : ts.Minutes.ToString()) + ":";
            message += ((ts.Seconds < 10) ? ("0" + ts.Seconds.ToString()) : ts.Seconds.ToString());

        }
        /// <summary>
        /// 提交按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (saveExam(false))
            {
                DatUser duser = Session["User"] as DatUser;
                string strSql = Session["trquestion"] == null ? "00000000-0000-0000-0000-000000000000" : Session["trquestion"].ToString();
                string strUserID = duser == null ? "00000000-0000-0000-0000-000000000000" : duser.UserID.ToString();
                string strTime = DateTime.Now.ToString("yyyy-MM-dd HH:ss");
                BaseBussnies bbesTemp = new BaseBussnies();
                bbesTemp.RunSqlCommand("update TrSendQuestion set QuestionEndTime='" + strTime + "' where TrQuestionnaireID='" + strSql + "'and ToUserID='" + strUserID + "'");

                ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "msg", "javascript:closeWins();", true);
            }
        }

        private bool saveExam(bool bls)
        {
            DatUser du = Session["User"] as DatUser;
            if (!bls)
            {
                string strTempExam = GetIstg(du);
                if (strTempExam == "1")
                {
                    return false;
                }
            }
           
            BaseBussnies bbesTemp = new BaseBussnies();
           
            string strSql = Session["trquestion"] == null ? "00000000-0000-0000-0000-000000000000" : Session["trquestion"].ToString();
            string strUserID = du == null ? "00000000-0000-0000-0000-000000000000" : du.UserID.ToString();
            string strTime = DateTime.Now.ToString("yyyy-MM-dd HH:ss");
            bbesTemp.RunSqlCommand("update TrSendQuestion set IsFinish='Y', QuestionStartTime='" + strTime + "' where TrQuestionnaireID='" + strSql + "'and ToUserID='" + strUserID + "'");
       
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                TextBox te = rptList.Items[i].FindControl("txtAnswer") as TextBox;
                HiddenField hdnFld = rptList.Items[i].FindControl("hdnQsid") as HiddenField;
                RadioButtonList rbl = rptList.Items[i].FindControl("rbtnAnswer") as RadioButtonList;
                CheckBoxList chk = rptList.Items[i].FindControl("chkAnswer") as CheckBoxList;
                TextBox txtExplain = rptList.Items[i].FindControl("txtExplain") as TextBox;
                if (hdnFld != null && du != null)
                {
                    TrQuestionAnswer tqa = new TrQuestionAnswer();
                    tqa.TrQuestionAnswerID = Guid.NewGuid();
                    tqa.TrQuestionnaireSubjectID = new Guid(hdnFld.Value);
                    tqa.AddTime = DateTime.Now;
                    if (te != null && te.Text != "")
                    {
                        tqa.AnswerContent = te.Text;
                    }
                    else if (rbl != null && rbl.SelectedIndex != -1)
                    {
                        tqa.AnswerContent = rbl.SelectedItem == null ? "" : rbl.SelectedItem.Text;
                    }
                    else if (chk != null && chk.SelectedIndex != -1)
                    {
                        string chkTemp = "";
                        for (int j = 0; j < chk.Items.Count; j++)
                        {
                            if (chk.Items[j].Selected)
                            {
                                if (j == chk.SelectedIndex)
                                {
                                    chkTemp += chk.Items[j].Text;
                                }
                                else { chkTemp += "," + chk.Items[j].Text; }
                            }
                        }
                        tqa.AnswerContent = chkTemp;
                    }
                    if (txtExplain!=null&&txtExplain.Text.Length>0)
                    {
                        tqa.AnswerContent = tqa.AnswerContent + "###：" + txtExplain.Text;
                    }
                    tqa.AnswerUserId = du.UserID;
                    BaseBussnies bbes = new BaseBussnies(tqa);
                    bbes.Insert();
                }
            }
            return true;
        }
        /// <summary>
        /// 是否可以跳过
        /// </summary>
        /// <param name="du"></param>
        private string GetIstg(DatUser du)
        {
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                TextBox te = rptList.Items[i].FindControl("txtAnswer") as TextBox;
                RadioButtonList rbl = rptList.Items[i].FindControl("rbtnAnswer") as RadioButtonList;
                CheckBoxList chk = rptList.Items[i].FindControl("chkAnswer") as CheckBoxList;
                HiddenField hdnJump = rptList.Items[i].FindControl("hdnJump") as HiddenField;
                if (du != null && hdnJump != null && hdnJump.Value == "N")
                {
                    string tempJump = "";
                    TrQuestionAnswer tqa = new TrQuestionAnswer();
                    if (te != null && te.Text != "")
                    {
                        tempJump = te.Text;
                    }
                    else if (rbl != null && rbl.SelectedIndex != -1)
                    {
                        tempJump = rbl.SelectedItem == null ? "" : rbl.SelectedItem.Text;
                    }
                    else if (chk != null && chk.SelectedIndex != -1)
                    {
                        string chkTemp = "";
                        for (int j = 0; j < chk.Items.Count; j++)
                        {
                            if (chk.Items[j].Selected)
                            {
                                if (j == chk.SelectedIndex)
                                {
                                    chkTemp += chk.Items[j].Text;
                                }
                                else { chkTemp += "," + chk.Items[j].Text; }
                            }
                        }
                        tempJump = chkTemp;
                    }
                    if (tempJump == "")
                    {
                        lblShow.Text = "<font color='Red'>第" + (i + 1) + "题为必填题，不能跳过</font>";
                        return "1";
                    }
                }
            } return "";
        }
        /// <summary>
        /// 上一题按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPre_Click(object sender, EventArgs e)
        {
            Session["nums"] = Convert.ToInt32(Session["nums"].ToString()) - 1;
            num = Convert.ToInt32(Session["nums"].ToString());
            btnNext.Enabled = true;
            if (num == 0)
            {
                btnPre.Enabled = false;
            }
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                if (i == num)
                {
                    this.rptList.Items[i].Visible = true;
                }
                else { this.rptList.Items[i].Visible = false; }
            }

        }
        /// <summary>
        /// 下一题按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNext_Click(object sender, EventArgs e)
        {

            //HiddenField hdnJump = rptList.Items[0].FindControl("hdnJump") as HiddenField;
            //TextBox te = rptList.Items[0].FindControl("txtAnswer") as TextBox;
            //if (hdnJump != null && te != null && hdnJump.Value != "Y" && te.Text.Trim() == "")
            //{
            //    Page.ClientScript.RegisterStartupScript(GetType(), "",
            //        "<script>alert('该题为必填题，不能跳过！')</script>");
            //} 
            btnNext.Enabled = true;
            if (Convert.ToInt32(Session["nums"].ToString()) == (Convert.ToInt32(Session["count"].ToString()) - 2))
            {
                btnNext.Enabled = false; num = Convert.ToInt32(Session["nums"].ToString()) + 1; Session["nums"] = Convert.ToInt32(Session["nums"].ToString()) + 1;
            }
            else { Session["nums"] = Convert.ToInt32(Session["nums"].ToString()) + 1; num = Convert.ToInt32(Session["nums"].ToString()); }



            btnPre.Enabled = true;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                if (i == num)
                {
                    this.rptList.Items[i].Visible = true;
                }
                else { this.rptList.Items[i].Visible = false; }
            }
        }
        /// <summary>
        /// 单选按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rbtnSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rbtnSelect.SelectedIndex == 0)
            {
                btnNext.Visible = false;
                btnPre.Visible = false;
                for (int i = 0; i < rptList.Items.Count; i++)
                {
                    this.rptList.Items[i].Visible = true;
                }
            }
            else
            {

                for (int i = 0; i < rptList.Items.Count; i++)
                {
                    if (i == 0)
                    {
                        this.rptList.Items[0].Visible = true;
                    }
                    else { this.rptList.Items[i].Visible = false; }
                }
                btnNext.Visible = true;
                btnPre.Visible = true;


            }
        }
        /// <summary>
        /// 控件绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lblType = e.Item.FindControl("lblType") as Label;
            TextBox te = e.Item.FindControl("txtAnswer") as TextBox;
            HiddenField hdnFld = e.Item.FindControl("hdnQid") as HiddenField;
            if (lblType != null && lblType.Text == "判断题")
            {
                RadioButtonList rbl = e.Item.FindControl("rbtnAnswer") as RadioButtonList;
                if (rbl != null)
                {
                    rbl.Visible = true;
                    bindYesOrNo(rbl);
                }
                te.Visible = false;
            }
            else if (lblType != null && (lblType.Text == "单选题" || lblType.Text == "多选题"))
            {
                Repeater rpt = e.Item.FindControl("rptItem") as Repeater;
                TextBox txtExplain = e.Item.FindControl("txtExplain") as TextBox;
                if (hdnFld != null)
                {
                    rpt.DataSource = bTrQuestionnaireSubject.GetSubjectInfoToItem(new Guid(hdnFld.Value));
                    rpt.DataBind();
                    if (lblType.Text == "单选题")
                    {
                        RadioButtonList rbl = e.Item.FindControl("rbtnAnswer") as RadioButtonList;
                        if (rbl != null)
                        {
                            rbl.Visible = true;
                            bindSingleSubject(rbl, new Guid(hdnFld.Value));
                            for (int i = 0; i < rbl.Items.Count; i++)
                            {
                                if (rbl.Items[i].Value == "其他" || rbl.Items[i].Value == "其它" || rbl.Items[i].Value == "其她")
                                {
                                    txtExplain.Visible = true;
                                } 
                            }
                        }
                    }
                    else if (lblType.Text == "多选题")
                    {
                        CheckBoxList chk = e.Item.FindControl("chkAnswer") as CheckBoxList;
                        if (chk != null)
                        {
                            chk.Visible = true;
                            bindCheckSubject(chk, new Guid(hdnFld.Value));
                            for (int i = 0; i < chk.Items.Count; i++)
                            {
                                if (chk.Items[i].Value == "其他" || chk.Items[i].Value == "其它" || chk.Items[i].Value == "其她")
                                {
                                    txtExplain.Visible = true;
                                }
                            }
                        }
                    }
                }
                te.Visible = false;
            }
        }
        private void bindSingleSubject(RadioButtonList rbl, Guid gd)
        {
            if (gd == null)
            {
                gd = Guid.NewGuid();
            }
            rbl.DataSource = bTrQuestionnaireSubject.GetSubjectInfoToItem(gd);
            rbl.DataTextField = "itemcode";
            rbl.DataValueField = "SunjectItem";
            rbl.DataBind();
        }
        private void bindCheckSubject(CheckBoxList chk, Guid gd)
        {
            if (gd == null)
            {
                gd = Guid.NewGuid();
            }
            chk.DataSource = bTrQuestionnaireSubject.GetSubjectInfoToItem(gd);
            chk.DataTextField = "itemcode";
            chk.DataValueField = "SunjectItem";
            chk.DataBind();
        }
        /// <summary>
        /// 初始化判断题选项
        /// </summary>
        /// <param name="rbl">RadioButtonList控件名</param>
        private void bindYesOrNo(RadioButtonList rbl)
        {
            ListItem liYes = new ListItem();
            liYes.Text = "对";
            liYes.Value = "对";
            rbl.Items.Add(liYes);
            ListItem liNo = new ListItem();
            liNo.Text = "错";
            liNo.Value = "错";
            rbl.Items.Add(liNo);
        }
        /// <summary>
        /// 返回是否必填
        /// </summary>
        /// <param name="obj">Y/N</param>
        /// <returns></returns>
        protected string GetIsJump(object obj)
        {
            if (obj != null && obj.ToString() == "N")
            {
                return "<font color='Red'>*必填</font>";
            }
            return "";
        }
    }
}